import {getUsername} from "./utils.js";
import {getRole} from "./utils.js";

function getNews() {
    $.ajax({
        url: "http://www.woniu-news.com:8082/getNewsList.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        dataType: "json",
        success: (resp) => {
            let context = ""
            if (resp.code === 200) {
                for (let item of resp.data) {
                    context += `
                        <tr>
                            <td>${item.title}</td>
                            <td>${item.time}</td>
                            <td class="actions">
                                <a href="edit_news.html?nid=${item.id}" class="edit">编辑</a>
                                <a href="javascript:void(0)" data-id="${item.id}" class="delete">删除</a>
                            </td>
                        </tr>
                        `
                }
            } else if (resp.code === 202) {
                context = `
                        <tr>
                            <td colspan="3">暂无数据</td>
                        </tr>
                    `
            }
            $(".tbody").html(context)
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}

function deleteNewsById(nid) {
    const username = getUsername()
    const role = getRole()

    $.ajax({
        url: "http://www.woniu-news.com:8082/deleteNewsById.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        data: {
            username,
            role,
            nid
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                alert(resp.message)
                getNews()
            } else {
                alert(resp.message)
            }
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}


getNews()
// 删除新闻事件监听
$(document).on("click", ".delete", function () {
    const nid = $(this).attr("data-id");
    deleteNewsById(nid);
});